package cn.wolfcode.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Component
public class TimeGatewayFilterFactory extends AbstractGatewayFilterFactory<TimeGatewayFilterFactory.Config> {
    public static final String PARTS_KEY = "parts";

    public TimeGatewayFilterFactory() {
        super(TimeGatewayFilterFactory.Config.class);
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(PARTS_KEY);
    }

    @Override
    public GatewayFilter apply(TimeGatewayFilterFactory.Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange,
                                     GatewayFilterChain chain) {

                /**
                 * 在filter方法内部写的代码就是前置逻辑
                 */
                //判断 对应 Parts的值 是否要进行拦截
                if(!config.isParts()){
                    return chain.filter(exchange);
                }

                // 获取时间 存放到上下文中
                exchange.getAttributes().put("beginTime",new Date().getTime());



                return chain.filter(exchange).then(Mono.fromRunnable(new Runnable() {
                    @Override
                    public void run() {
                        /**
                         * 后置逻辑
                         */
                        Long endTime =  new Date().getTime();
                        Long beginTime = (Long) exchange.getAttributes().get("beginTime");
                        System.out.println("最终耗时" + (endTime - beginTime) + "ms");

                    }
                }));
            }

        };
    }

    public static class Config {

        private boolean parts;

        //获取对应配置中的值
        public boolean isParts() {
            return parts;
        }

        public void setParts(boolean parts) {
            this.parts = parts;
        }

    }
}
